package com.htjc.integral.interactionouter.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Component;

import com.htjc.integral.common.util.Constance;
import com.htjc.integral.common.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 电e宝处理请求内网
 * @author kuangxz-gs
 */
@Slf4j(topic="outerLogger")
@Component
public class DebHandleCallInner {
	@Autowired
	public DataSource dataSource;//自动注入数据源
	@Autowired
    private Environment env;
	
	public String execute (String requrl, String reqbody) {
		log.info(DebHandleCallInner.class.getName()+"方法名：execute()渠道端外网应用积分e+外网服务接口=====start=====");

		String resultMsg = null;//定义返回对象
		String msgCode = null; // 返回信息码
		String msgStr = null; //返回信息码对应信息
		
		String callCode = null; //数据库请求Code
		
		Connection conn = null;//数据连接
		CallableStatement cstmt = null;//存储过程执行器
		PreparedStatement preparedStatement = null;//常用执行器
		ResultSet resultSet = null;//结果存储器
		
		try {
			log.info("{}调用内网系统接口服务,地址：{}",requrl);
			
			conn = dataSource.getConnection();//获取连接对象
			cstmt = conn.prepareCall( "{ CALL " +env.getProperty("call_name") + "(?,?,?,?,?)}");
			//设置连接参数及调用信息
			cstmt.setQueryTimeout(120);
			cstmt.setString(1, requrl);
			log.info("{}调用内网系统接口服务,地址：{}报文："+reqbody);
			cstmt.setString(2, reqbody);
			cstmt.registerOutParameter(3, Types.VARCHAR);
			cstmt.registerOutParameter(4, Types.FLOAT);
			cstmt.registerOutParameter(5, Types.VARCHAR);
			cstmt.executeQuery();
			
			//获取存储过程返回结果
			resultMsg = cstmt.getString(3);
			callCode = cstmt.getString(4);
			
			log.info("{}：调用内网返回结果：{}",resultMsg);
			
			//返回数据为空，直接抛出异常
			if (StringUtil.isNull(resultMsg)) {
				throw new CustomRuntimeException("调用存储过程返回结果为空");
			}
			
			//如果获取到的值含有TEMPDATA 则要去数据库里面查询值
			if (resultMsg.startsWith(Constance.WEBSERVICES_TEMPDATA_NAME)) {
				//创建执行对象
				preparedStatement = conn.prepareStatement(env.getProperty("call_webservices_temp_sql"));
				//设置参数里的id
				preparedStatement.setString(1, resultMsg.substring(Constance.WEBSERVICES_TEMPDATA_NAME.length() + 1));
				//执行查询获取结果
				resultSet = preparedStatement.executeQuery();
				//如果结果不为空，将结果取出来
				if (resultSet != null) {
					resultSet.next();
					resultMsg = StringUtil.ClobToString(resultSet.getClob(1));
				}
				log.info("{}：返回数据id,根据数据查询返回解析数据：{}",resultMsg);
				//返回数据为空，直接抛出异常
				if (StringUtil.isNull(resultMsg)) {
					throw new CustomRuntimeException("通过存储过程取得的id查询结果返回结果为空");
				}
			}
			
			msgCode = null;
		} catch (CustomRuntimeException e) {
			resultMsg = null; //将返回信息置为空
			log.info("{}:{}",e.getMessage());
		} catch (Exception e) {
			log.error("{}:调用内网服务出现异常",e);
		} finally {
			JdbcUtils.closeResultSet(resultSet);
			JdbcUtils.closeStatement(cstmt);
			JdbcUtils.closeStatement(preparedStatement);
			DataSourceUtils.releaseConnection(conn, dataSource);
		}
		
		//判断有没有错误，有的话取出错误信息并组装返回报文
		if (!StringUtil.isNull(msgCode)) {
//			msgStr = SystemConfig.getConfig(msgCode);
			resultMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><RESMES><RETURN_CODE>" + msgCode + "</RETURN_CODE><RETURN_MSG>" + msgStr + "</RETURN_MSG></RESMES>";
		}
		log.info("返回值："+resultMsg);

		log.info(DebHandleCallInner.class.getName()+"方法名：execute()渠道端外网应用积分e+外网服务接口=====end=====");
		return resultMsg;
	}

}
